package com.xuecheng.manage_cms_client.service;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.manage_cms_client.dao.CmsPageRepository;
import com.xuecheng.manage_cms_client.dao.CmsSiteRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Optional;

/**
 * @author: gongfy
 * @create: 2020/7/16 10:40
 * @Description:
 */
@Service
@Slf4j
public class PageService {

    @Autowired
    private CmsPageRepository cmsPageRepository;
    @Autowired
    private  CmsSiteRepository cmsSiteRepository;
    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Autowired
    private GridFSBucket gridFSBucket;

    //将页面html保存到页面物理路径
    public void saveHtmlToPhysicalPath(String pageId) {
        // 1.根据pegeId查询Cmspage
        CmsPage cmsPage = this.findCmsPageById(pageId);
        //2.查询页面所属站点
        CmsSite cmsSite = this.findCmsSiteById(cmsPage.getSiteId());
        //查询html静态文件Id fileId
        String fileId = cmsPage.getHtmlFileId();
        //fileId从Gridfs查询页面html文件
        InputStream inputStream = this.getFileById(fileId);
        if (inputStream == null){
            log.error("getFileById inputstream is null ,fileId：{}",fileId);
            return;
        }
        //2.将html文件内容保存到服务器物理路径上
        //页面路径 =站点物理路径+页面物理路径(相对路径)+页面名称
        String pagePath = cmsSite.getSitePhysicalPath()+cmsPage.getPagePhysicalPath()+cmsPage.getPageName();
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(new File(pagePath));
            //将文件内容保存到服务物理路径
            IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                outputStream.close(); // todo 放在一个try catch里面关闭流还是分开关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //根据文件fileId获取文件内容

    public InputStream getFileById(String fileId){
        //1.从MongoDB中获取文件对象  todo 怎么判断是从哪个数据库中查询的
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
        //2.打开下载流（继承inputstream）  todo getObjectId是获取的什么
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //3.定义GridFsResource
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
        try {
            InputStream inputStream = gridFsResource.getInputStream();
            return inputStream;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //根据站点id得到站点
    public CmsSite findCmsSiteById(String siteId){
        Optional<CmsSite> cmsSiteOptional = cmsSiteRepository.findById(siteId);
        if (cmsSiteOptional.isPresent()){
            CmsSite cmsSite = cmsSiteOptional.get();
            return cmsSite;
        }
        return null;
    }

    public CmsPage findCmsPageById(String pageId){
        Optional<CmsPage> cmsPageOptional = cmsPageRepository.findById(pageId);
        if (!cmsPageOptional.isPresent()){
            ExceptionCast.cast(CommonCode.CMSPAGE_NOTEXISTS);
        }
        return cmsPageOptional.get();
    }


}
